<template>
  <div class="app-container">
    <template>
      <el-row>
        <el-col :span="24">
          <div class="h_top">
            <div class="search_box">
              <el-form :model="query" :inline="true">
                <el-row :gutter="10">
                  <el-col :xl="3" :lg="3" :md="7" :sm="8">
                    <el-form-item>
                      <div class="search_label">编 号</div>
                      <el-input v-model="query.coding" size="mini" @keyup.enter.native="search" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="3" :lg="3" :md="7" :sm="8">
                    <el-form-item>
                      <div class="search_label">名 称</div>
                      <el-input v-model="query.name" size="mini" @keyup.enter.native="search" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="3" :lg="3" :md="7" :sm="8">
                    <el-form-item>
                      <div class="search_label">状 态</div>
                      <el-select v-model="query.status" size="mini">
                        <el-option v-for="(item, orderIndex) in orderPartsStatus" :key="orderIndex" :label="item" :value="orderIndex" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xl="3" :lg="3" :md="7" :sm="8">
                    <el-form-item>
                      <div class="search_label">来 源</div>
                      <el-select v-model="query.type" size="mini">
                        <el-option v-for="(item, fromIndex) in fromType" :key="fromIndex" :label="item" :value="fromIndex" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xl="3" :lg="3" :md="5" :sm="6">
                    <el-form-item>
                      <div class="search_label">创建时间</div>
                      <el-date-picker v-model="query.create_time" type="datetimerange" placeholder="" value-format="yyyy-MM-dd HH:mm:ss" size="mini" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="3" :lg="3" :md="5" :sm="6">
                    <el-form-item>
                      <div class="search_label">验证时间</div>
                      <el-date-picker v-model="query.verify_date" type="datetimerange" placeholder="" value-format="yyyy-MM-dd HH:mm:ss" size="mini" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="2" :md="2" :sm="2">
                    <el-form-item>
                      <div class="search_label">操 作</div>
                      <el-button type="primary" icon="el-icon-search" size="mini" @click="search">查找</el-button>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
            <div class="toolBars">
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-document-add" size="mini" @click="addHandler">增加</el-button>
              </div>
              <div class="buttonBox" hidden>
                <el-button type="primary" icon="el-icon-printer" size="mini" @click="dialogTableVisible = true">导出</el-button>
                <el-dialog title="工具入库导出" :visible.sync="dialogTableVisible" width="45%" center>
                  <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" class="marginLeft20" @change="handleCheckAllChange">全选</el-checkbox>
                  <el-checkbox-group v-model="needExport" class="marginLeft20" @change="handleText">
                    <el-checkbox v-for="item in needExportArray" :key="item" class="width73" checked :label="item">{{ item }}</el-checkbox>
                  </el-checkbox-group>
                  <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogTableVisible = false">取 消</el-button>
                    <el-button type="primary" @click="exportHandler">确 定</el-button>
                  </div>
                </el-dialog>
              </div>
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-box" size="mini" :disabled="!selection.length" @click="archive">归档</el-button>
              </div>
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-delete" size="mini" :disabled="!selection.length" @click="remove">删除</el-button>
              </div>
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-refresh" size="mini" @click="reloadHandler">刷新</el-button>
              </div>
              <div class="fr">总数：<span>{{ total }}</span></div>
            </div>
          </div>
        </el-col>
      </el-row>
    </template>
    <div>
      <el-table v-loading="loading" :data="enterList" size="small" stripe border :header-cell-style="{background:'#eef1f6',color:'#606266'}" style="width: 100%" @selection-change="selectionHandler">
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column prop="coding" label="编号" min-width="25%" align="center" />
        <el-table-column prop="name" label="名称" min-width="25%" align="center" />
        <el-table-column prop="status" label="状态" min-width="25%" align="center" :formatter="statusFormat" />
        <el-table-column prop="create_time" label="创建时间" width="200" align="center" />
        <el-table-column prop="verify_date" label="验证时间" width="200" align="center" />
        <el-table-column prop="type" label="来源" min-width="25%" align="center" :formatter="typeFormat" />
        <el-table-column v-if="listHandle" fixed="right" label="操作" width="200" align="center">
          <template scope="scope">
            <el-button type="primary" size="mini" @click="updateHandler(scope.row.id)">编辑</el-button>
            <el-button type="danger" size="mini" @click="confirmDel(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination class="page" background :page-size="query.limit" layout="total,prev,pager,next,jumper" :total="total" :current-page.sync="query.page" @current-change="index" @size-change="index" />
    </div>
  </div>
</template>
<script>
import API from '@/api/tool/enter'
import { orderPartsStatus, fromType } from '@/utils/options'
import xlsx from 'xlsx'
import exportMethod from '@/mixins/export'
export default {
  inject: ['reload', 'goUrl', 'delOne', 'delMany', 'getEnterPartsFormat', 'getEnterFormat', 'archives'],
  components: {},
  mixins: [exportMethod],
  data() {
    return {
      checkAll: true,
      isIndeterminate: true,
      dialogTableVisible: false,
      needExport: [],
      needExportArray: ['编号', '名称', '状态', '仓库', '验证人员', '验证时间', '来源', '入库工具'],
      loading: false,
      total: 0,
      query: { page: 1, limit: 15 },
      enterList: [],
      selection: [],
      orderPartsStatus,
      fromType
    }
  },
  computed: {
    tableMaxHeight() {
      return window.innerHeight - 260 + 'px'
    },
    listHandle() {
      return this.$store.state.settings.listHandle
    }
  },
  watch: {},
  created() {
    const query = JSON.parse(sessionStorage.getItem('query'))
    if (query) {
      this.query = query
      sessionStorage.removeItem('query')
    }
    this.index()
  },
  methods: {
    search() {
      this.query.page = 1
      this.index()
    },
    selectionHandler(selection) {
      this.selection = selection
    },
    index() {
      this.loading = true
      API.enterList(this.query).then(response => {
        this.total = response.data.total
        this.enterList = response.data.data
      }).finally(() => {
        this.loading = false
      })
    },
    handleCheckAllChange(val) {
      this.needExport = val ? this.needExportArray : []
      this.isIndeterminate = false
    },
    handleText(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.needExportArray.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.needExportArray.length
    },
    exportHandler() {
      if (this.selection.length === 0) {
        this.$message.error('请选择要到导出的数据')
        return false
      }
      this.selection.forEach((item) => {
        if (item.status === 0) {
          item.statusOut = '创建'
        } else if (item.status === 1) {
          item.statusOut = '在执行'
        } else if (item.status === 2) {
          item.statusOut = '审核完成'
        } else if (item.status === 3) {
          item.statusOut = '归档'
        }
        if (item.type === 0) {
          item.typeOut = '一般'
        } else if (item.type === 1) {
          item.typeOut = '赠予'
        }
        if (item.verify_admin) {
          item.v_name = item.verify_admin.name
          item.v_date = item.verify_date
        } else {
          item.v_name = '未审核'
          item.v_date = '未审核'
        }
        console.log(item)
        if (item.tool_list) {
          let thisPart = []
          item.tool_listOut = ''
          item.tool_list.forEach((tool_listItem) => {
            if (item.tool_list.length > 1) {
              if (item.type === 0) {
                thisPart = `采购订单（${tool_listItem.orders.name}），工具（${tool_listItem.tools_true.name}），供应商（${tool_listItem.providers.name}），单位（${tool_listItem.tools_true.unit}），入库数量（${tool_listItem.number}），采购单价（${tool_listItem.price}），合计（${tool_listItem.total_price}），提报数量（${tool_listItem.need_number}），提报时间（${tool_listItem.create_time}），提报单位（${tool_listItem.orders.admin.department.name}），提报人（${tool_listItem.orders.admin.true_name}）|`
              } else {
                thisPart = `工具（${tool_listItem.tools_true.name}），单位（${tool_listItem.tools_true.unit}），入库数量（${tool_listItem.number}）`
              }
              item.tool_listOut = item.tool_listOut + thisPart
            } else {
              if (item.type === 0) {
                thisPart = `采购订单（${tool_listItem.orders.name}），工具（${tool_listItem.tools_true.name}），供应商（${tool_listItem.providers.name}），单位（${tool_listItem.tools_true.unit}），入库数量（${tool_listItem.number}），采购单价（${tool_listItem.price}），合计（${tool_listItem.total_price}），提报数量（${tool_listItem.need_number}），提报时间（${tool_listItem.create_time}），提报单位（${tool_listItem.orders.admin.department.name}），提报人（${tool_listItem.orders.admin.true_name}）`
              } else {
                thisPart = `工具（${tool_listItem.tools_true.name}），单位（${tool_listItem.tools_true.unit}），入库数量（${tool_listItem.number}）`
              }
              item.tool_listOut = thisPart
            }
          })
          if (item.tool_list.length > 1) {
            item.tool_listOut = item.tool_listOut.substr(0, item.tool_listOut.length - 1)
          }
        } else {
          item.tool_listOut = '暂无'
        }
      })
      const data = []
      const titleObj = {
        'coding': '编号',
        'name': '名称',
        'statusOut': '状态',
        'stores.name': '仓库',
        'v_name': '验证人员',
        'v_date': '验证时间',
        'typeOut': '来源',
        'tool_listOut': '入库工具'
      }
      if (this.needExport.length) {
        const title = []
        for (const key of this.needExport) {
          title.push(key)
        }
        data.push(title)
      } else {
        data.push(Object.values(titleObj))
      }
      const excelNeedExport = []
      for (const keys of this.needExport) {
        const thisKey = Object.keys(titleObj).find(key => titleObj[key] === keys)
        excelNeedExport.push(thisKey)
      }
      let fieldOut = 1
      this.selection.forEach((item) => {
        if (excelNeedExport.length) {
          const d = []
          for (const key of excelNeedExport) {
            if (key.includes('.')) {
              let value = item
              const tag = key.split('.')
              for (const k of tag) {
                value = value[k]
              }
              d.push(value)
            } else {
              d.push(item[key])
            }
          }
          data.push(d)
        } else {
          this.$message.error('请选择要到导出的字段')
          fieldOut = 2
        }
      })
      if (fieldOut === 1) {
        const workbook = {
          SheetNames: ['toolEnter'],
          Sheets: {
            'toolEnter': xlsx.utils.aoa_to_sheet(data)
          }
        }
        this.exportExec(workbook, '工具收货入库数据报表.xlsx')
      }
    },
    archive() {
      const selection = this.selection
      this.archives(API, selection)
    },
    remove() {
      const selection = this.selection
      this.delMany(API, selection)
    },
    confirmDel(id) {
      this.delOne(API, id, false)
    },
    addHandler() {
      this.goUrl('/tool/enter/enter_add')
    },
    updateHandler(id) {
      sessionStorage.setItem('query', JSON.stringify(this.query))
      const url = `/tool/enter/enter_edit/${id}`
      this.goUrl(url)
    },
    reloadHandler() {
      this.reload()
    },
    statusFormat(row) {
      return this.getEnterPartsFormat(row)
    },
    typeFormat(row) {
      return this.getEnterFormat(row)
    }
  }
}
</script>
